package org.iartisan.wechatsdk.miniprogram

import java.security.AlgorithmParameters
import java.util

import javax.crypto.Cipher
import javax.crypto.spec.{IvParameterSpec, SecretKeySpec}
import org.apache.commons.codec.binary.Base64

/**
  * 微信解密服务
  *
  * @author King  2019/6/19
  */
object WXBizDataCrypt {


  def decrypt(encryptedData: String, sessionKey: String, iv: String) = {
    val params = AlgorithmParameters.getInstance("AES")
    params.init(new IvParameterSpec(Base64.decodeBase64(iv)))
    val cipher = Cipher.getInstance("AES/CBC/NoPadding")
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES"), params)
    try {
      val resultByte = cipher.doFinal(Base64.decodeBase64(encryptedData))
      new String(decode(resultByte))
    } catch {
      case e: Exception => throw new IllegalArgumentException("解密失败：" + e.getMessage, e)
    }
  }

  /**
    * 删除解密后明文的补位字符.
    *
    * @param decrypted 解密后的明文
    * @return 删除补位字符后的明文
    */
  private def decode(decrypted: Array[Byte]) = {
    var pad = decrypted(decrypted.length - 1)
    if (pad < 1 || pad > 32) pad = 0
    util.Arrays.copyOfRange(decrypted, 0, decrypted.length - pad)
  }

}
